package main.www.wonderfuldata.servlet;


import main.www.wonderfuldata.PreparedStatement.JDBCUtils;
import main.www.wonderfuldata.PreparedStatement.PreparedStatementTest;
import main.www.wonderfuldata.bean.User2;
import main.www.wonderfuldata.com.StatementTest;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;



@WebServlet(name = "userRegistered",urlPatterns = "/userRegistered")
public class userRegistered extends HttpServlet {


    public void service(HttpServletRequest request, HttpServletResponse response) throws IOException {

        request.setCharacterEncoding("utf8");

        String nameRegister = request.getParameter("nameRegister");
        String passwordRegisterFirst = request.getParameter("passwordRegisterFirst");
        String passwordRegisterSecond = request.getParameter("passwordRegisterSecond");


        if(!passwordRegisterFirst.equals(passwordRegisterSecond)){
            System.out.println("两次输入的密码不相同，请重新输入。");
            //返回注册页面
            response.setHeader("Refresh","2;url=index.html");

        }else{
            //PreparedStatementTest pt = new PreparedStatementTest();
            StatementTest st = new StatementTest();

            String sql = "select * from User where name = ?";

            User2 user = st.getInstance(User2.class,sql,nameRegister);



            if (user != null){
                System.out.println("用户已经存在。");
                //返回注册页面
                response.setHeader("Refresh","2;url=index.html");

            }else {
                //查询不到对象才能添加用户
                PreparedStatementTest pt = new PreparedStatementTest();

                String sqlInsert = "insert into User(name,password) values(?,?)";
                //获取连接执行sql语句
                pt.update(sqlInsert,nameRegister,passwordRegisterFirst);
                //直接登录
                response.setHeader("Refresh","2;url=success.jsp?name="+nameRegister+"password="+passwordRegisterFirst);
            }
        }
    }
}
